What do you suppose happens if the user types in
an integer value, like 211
?
The characters are converted into a double
.
The input characters are converted into a
double
, if that is possible, even if
the input characters lack a decimal point.
If the input characters can NOT be converted into a
double
,
then Java throws an exception and the program halts.
(A later chapter will discuss how to deal with exceptions.)
For example:
C:\temp>java DoubleDouble Enter a double: rats Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextDouble(Unknown Source) at DoubleDouble.main(DoubleDouble.java:14)
The input might start with characters that can be converted,
followed by one or more spaces and perhaps additional characters.
If that happens,
nextDouble()
scans in only the characters that can be converted.
C:\temp>java DoubleDouble Enter a double: 3.14 and more characters value: 3.14 twice value: 6.28
If the program had another call to nextDouble()
it would start where the previous call stopped and
would find characters that can't be converted,
and would throw an exception.
Will the following input work with the above program?
C:\temp>java DoubleDouble Enter a double: -97.65